package com.aptemo.webetek.server.workers;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.server.CommonService;
import com.aptemo.webetek.server.data.PMF;

public class EmailSenderWorker
		extends HttpServlet
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 7960205115503427515L;

	private static String		WEBETEK_ADMIN_EMAIL	= "webetek.online@gmail.com";

	private static final Logger	log					= Logger.getLogger(EmailSenderWorker.class.getName());

	private CommonService		utils				= new CommonService();

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		String from = req.getParameter("from");
		String to = req.getParameter("to");
		String cc = req.getParameter("cc");
		String subject = req.getParameter("subject");
		String content = req.getParameter("content");
		String header = req.getParameter("header");
		String footer = req.getParameter("footer");

		if (from == null || from.isEmpty())
		{
			from = WEBETEK_ADMIN_EMAIL;
		}

		content = decorateContent(header, content, footer);

		try
		{
			utils.sendEmail(from, to, cc, subject, content);
		}
		catch (BackendException e)
		{
			e.printStackTrace();
			log.severe(e.getLocalizedMessage());
		}

	}

	private String decorateContent(String header, String content, String footer)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			String body = "";

			if (header != null && !header.isEmpty())
			{
				body += header;
				body += "\r\n";
				body += "\r\n";
			}

			body += content;
			body += "\r\n";
			body += "\r\n";

			if (footer != null && !footer.isEmpty())
			{
				body += footer;
				body += "\r\n";
				body += "\r\n";
			}

			return body;
		}
		finally
		{
			pm.close();
		}
	}
}
